package com.chat.view;

import com.chat.FileAddress;
import com.chat.Local;
import com.chat.common.Message;
import com.chat.common.MessageType;
import com.chat.common.User;
import com.chat.io.*;
import com.chat.service.*;
import com.chat.utils.*;
import javafx.application.Platform;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.collections.transformation.FilteredList;
import javafx.fxml.FXMLLoader;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.ScrollPane;
import javafx.scene.control.TextArea;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.input.KeyCode;
import javafx.scene.input.KeyEvent;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.*;
import javafx.scene.text.Font;
import javafx.stage.Stage;
import javafx.stage.StageStyle;
import javafx.util.Callback;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.List;
import java.util.function.Predicate;
public class MainWindowController {
    public Label ceshi;
    public ListView listview;
    public ListView chatlist;
    public Label nickname;
    public Label qianming;
    public TextArea inputbox;
    public ImageView headpicture;
    public AnchorPane chatpane;
    public AnchorPane chatpane1;
    public String receive;//当前点开的用户的id
    public String receivenickname;
    public String flag;//标记是群聊还是私聊
    public Button createbutton;
    public BorderPane common;
    public Label receivelabel;
    public VBox express;
    public ScrollPane ss;
    public TextArea search;

    public static ObservableList<FriendListData> friend= FXCollections.observableArrayList();
    public static ObservableList<ChatListData> chat=FXCollections.observableArrayList();


    public void initialize(){
        {   express.setVisible(false);
            ss.setVisible(false);
            chatpane.setVisible(false);
            chatpane1.setVisible(false);
            chatlist.getItems().clear();
            chat.clear();
            listview.getItems().clear();
            friend.clear();
            //拉取好友列表
            new GetFriendList(friend);
            //拉取群列表
            GetGroupList ggl = new GetGroupList();
            ggl.getgrouplist();
            //获取常用语列表
            CommonPharse commonPharse=new CommonPharse();
            commonPharse.get(Local.user.getUsername());
            try {
                Thread.sleep(500);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            {
                File file1 = new File("D:/chatproject/client/" + Local.user.getUsername() + ".png");
                headpicture.setClip(new SetCircle().getRectangle(40,40));
                headpicture.setImage(new Image("file:" + file1.getAbsolutePath()));
                nickname.setText(Local.user.getNickname());
                if (Local.user.getQianming() == null)
                    qianming.setText("这个人很懒，什么也没有留下");
                else qianming.setText(Local.user.getQianming());
            }

            listview.getSelectionModel().setSelectionMode(SelectionMode.SINGLE);//设成单选

            listview.setItems(friend);

            chatlist.setItems(chat);
        }//初始化信息

        listview.setCellFactory(new Callback<ListView, ListCell>() {
            @Override
            public ListCell call(ListView param) {
                return new ListCell<FriendListData>(){
                    @Override
                    protected void updateItem(FriendListData item, boolean empty){
                        super.updateItem(item,empty);
                        if(!empty){
                            HBox hbox=new HBox();
                            FXMLLoader fxmlLoader=new FXMLLoader();
                            fxmlLoader.setLocation(getClass().getResource("friendlist.fxml"));
                            try {
                                hbox.getChildren().add(fxmlLoader.load());
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                            setOnMouseClicked(event ->{//设置每个list的点击事件
                                express.setVisible(false);
                                ss.setVisible(false);
                                if(item.getId().equals("验证消息"))//如果点击的是验证消息，就打开验证消息对话框
                                {
                                    try {
                                        VerifyMessageView.start(new Stage());
                                    } catch (IOException e) {
                                        e.printStackTrace();
                                    }
                                }
                                else if(!Objects.equals(receive, item.getId())){//如果点的是同一个item，就不用刷新
                                    chatpane.setVisible(true);
                                    chatpane1.setVisible(true);
                                    chatlist.getItems().clear();//清空聊天框
                                    chat.clear();
                                    receive=item.getId();
                                    receivelabel.setText(item.getNickname());
                                    receivenickname=item.getNickname();
                                    Local.receive=receive;
                                    Local.receivenickname=receivenickname;
                                    System.out.println("加载消息记录");
                                    if(Objects.equals(item.getState(), "1")) {//如果是私聊的情况
                                        chatlist.scrollTo(chatlist.getItems().size());
                                        flag="1";
                                        GetHistoryMsg ghm = new GetHistoryMsg();
                                        ghm.gethistorymsg(Local.user.getUsername(), receive);
                                        chatlist.scrollTo(chatlist.getItems().size());
                                    }
                                    else if(Objects.equals(item.getState(), "0")){//如果是群聊的情况
                                        chatlist.scrollTo(chatlist.getItems().size());
                                        flag="0";
                                          GetGroupHistoryMsg gghm=new GetGroupHistoryMsg();
                                          gghm.get(receive);
                                         chatlist.scrollTo(chatlist.getItems().size());
                                    }
                                }
                            });
                            FriendListController friendListController=fxmlLoader.getController();
                            hbox.setPadding(new Insets(20,0,0,0));
                            hbox.setPrefHeight(50);
                            friendListController.setStatus(item.status);
                            friendListController.setId(item.getNickname());//放置昵称
                            friendListController.setQianming(item.qianming);//放置签名
                            friendListController.setId1(item.getId());
                            friendListController.setTouxiang(item.getId());
                            friendListController.setState(item.getState());
                            Platform.runLater(()-> {
                                this.setGraphic(hbox);
                            });

                        }
                        else {
                            Platform.runLater(()-> {
                                this.setGraphic(null);
                            });

                        }
                    }
                };
            }
        });

        chatlist.setCellFactory(new Callback<ListView, ListCell>() {
            @Override
            public ListCell call(ListView param) {
                return new ListCell<ChatListData>(){
                    @Override
                    protected void updateItem(ChatListData item, boolean empty){
                        super.updateItem(item,empty);
                        setStyle("-fx-background-color:transparent");
                        if(!empty&& Objects.equals(item.id, Local.user.getUsername())&& Objects.equals(item.type, "1")){//当信息发送者是自己并且是文本时
                            HBox hbox=new HBox();
                            hbox.setAlignment(Pos.TOP_RIGHT);
                            FXMLLoader fxmlLoader=new FXMLLoader();
                            fxmlLoader.setLocation(getClass().getResource("chatlistright.fxml"));
                            try {
                                hbox.getChildren().add(fxmlLoader.load());
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                            ChatListRightController chatlistController=fxmlLoader.getController();
                            hbox.setPrefHeight(USE_COMPUTED_SIZE);
                            chatlistController.setContectText(item.getContent());
                            chatlistController.setNickname(item.nickname);
                            chatlistController.setId(item.getId());
                            chatlistController.setTouxiang(item.getId());
                            chatlistController.setTime(item.time);
                            Platform.runLater(()-> {
                                this.setGraphic(hbox);
                            });
                        }
                        else if(!empty&& Objects.equals(item.id, Local.user.getUsername())&& Objects.equals(item.type, "2")){
                            HBox hbox=new HBox();
                            hbox.setAlignment(Pos.TOP_RIGHT);
                            FXMLLoader fxmlLoader=new FXMLLoader();
                            fxmlLoader.setLocation(getClass().getResource("chatrightimage.fxml"));
                            try {
                                hbox.getChildren().add(fxmlLoader.load());
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                                hbox.setPrefHeight(140);
                            ChatRightImageController chatRightImageController=fxmlLoader.getController();
                            chatRightImageController.setNickname(item.nickname);
                            chatRightImageController.setId(item.getId());
                            chatRightImageController.setTouxiang(item.getId());
                            chatRightImageController.setContent(item.filename);
                            chatRightImageController.setTime(item.time);
                            Platform.runLater(()-> {
                                this.setGraphic(hbox);
                            });
                        }
                        else if(!empty&& Objects.equals(item.id, Local.user.getUsername())&& Objects.equals(item.type, "3")){//自己发的文件
                            HBox hbox=new HBox();
                            hbox.setAlignment(Pos.TOP_RIGHT);
                            FXMLLoader fxmlLoader=new FXMLLoader();
                            fxmlLoader.setLocation(getClass().getResource("chatrightfile.fxml"));
                            try {
                                hbox.getChildren().add(fxmlLoader.load());
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                            hbox.setPrefHeight(140);
                            ChatRightFileController chatRightFileController=fxmlLoader.getController();
                            File file1=new File(FileAddress.LOCAL_WARHOUSE +item.fileaddress);
                            if(file1.exists()){
                                chatRightFileController.receivebutton.setText("打开文件");
                            }else chatRightFileController.receivebutton.setText("下载并打开");
                            chatRightFileController.setFileaddress(item.fileaddress);
                            chatRightFileController.setNickname(item.nickname);
                            chatRightFileController.setUserid(item.getId());
                            chatRightFileController.setTouxiang(item.getId());
                            chatRightFileController.setFilename(item.filename);
                            chatRightFileController.setTime(item.time);
                            Platform.runLater(()-> {
                                this.setGraphic(hbox);
                            });
                        }
                        else if(!empty&& !Objects.equals(item.id, Local.user.getUsername()) && Objects.equals(item.type, "1")){//当信息发送者是对方并且是文字时时
                            HBox hbox=new HBox();
                            hbox.setAlignment(Pos.TOP_LEFT);
                            FXMLLoader fxmlLoader=new FXMLLoader();
                            fxmlLoader.setLocation(getClass().getResource("chatlistleft.fxml"));
                            try {
                                hbox.getChildren().add(fxmlLoader.load());
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                            ChatListLeftController chatlistController=fxmlLoader.getController();
                            hbox.setPrefHeight(USE_COMPUTED_SIZE);
                            chatlistController.setContectText(item.getContent());
                            chatlistController.setNickname(item.nickname);
                            chatlistController.setId(item.getId());
                            chatlistController.setTouxiang(item.getId());
                            chatlistController.setTime(item.time);
                            Platform.runLater(()-> {
                                this.setGraphic(hbox);
                            });
                        }
                        else if(!empty&& !Objects.equals(item.id, Local.user.getUsername()) && Objects.equals(item.type, "2")){
                            HBox hbox=new HBox();
                            hbox.setAlignment(Pos.TOP_LEFT);
                            FXMLLoader fxmlLoader=new FXMLLoader();
                            fxmlLoader.setLocation(getClass().getResource("chatleftimage.fxml"));
                            try {
                                hbox.getChildren().add(fxmlLoader.load());
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                            hbox.setPrefHeight(140);
                            ChatLeftImageController chatLeftImageController=fxmlLoader.getController();
                            chatLeftImageController.setNickname(item.nickname);
                            chatLeftImageController.setId(item.getId());
                            chatLeftImageController.setTouxiang(item.getId());
                            chatLeftImageController.setContent(item.filename);
                            chatLeftImageController.setTime(item.time);
                            Platform.runLater(()-> {
                                this.setGraphic(hbox);
                            });
                        }
                        else if(!empty&& !Objects.equals(item.id, Local.user.getUsername()) && Objects.equals(item.type, "3")){//别人发的文件
                            HBox hbox=new HBox();
                            hbox.setAlignment(Pos.TOP_LEFT);
                            FXMLLoader fxmlLoader=new FXMLLoader();
                            fxmlLoader.setLocation(getClass().getResource("chatleftfile.fxml"));
                            try {
                                hbox.getChildren().add(fxmlLoader.load());
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                            hbox.setPrefHeight(140);
                            ChatLeftFileController chatLeftFileController=fxmlLoader.getController();
                            File file1=new File(FileAddress.LOCAL_WARHOUSE +item.fileaddress);
                            if(file1.exists()){
                                  chatLeftFileController.receivebutton.setText("打开文件");
                            }else chatLeftFileController.receivebutton.setText("接收并打开文件");
                            chatLeftFileController.setNickname(item.nickname);
                            chatLeftFileController.setUserid(item.getId());
                            chatLeftFileController.setTouxiang(item.getId());
                            chatLeftFileController.setAddress(item.fileaddress);
                            chatLeftFileController.setFile(item.file);
                            chatLeftFileController.setFilename(item.filename);
                            chatLeftFileController.setTime(item.time);
                            Platform.runLater(()-> {
                                this.setGraphic(hbox);
                            });
                        }
                        else {
                            Platform.runLater(()-> {
                                this.setGraphic(null);
                            });

                        }
                    }
                };
            }
        });
            getComboBox(common);//调用常用语的下拉列表

        search.textProperty().addListener(((observable, oldValue, newValue) -> {
               FilteredList<FriendListData> filteredList=friend.filtered(new Predicate<FriendListData>() {
                   @Override
                   public boolean test(FriendListData data) {
                        if(data.getId().equals(newValue)||data.getQianming().equals(newValue)){
                            return true;
                        }else{
                             return false;
                        }
                   }
               });
               listview.setItems(filteredList);
               if(newValue.isEmpty()){
                   listview.setItems(friend);
               }
        }));
        inputbox.setOnMouseClicked(event ->{//设置每个list的点击事件
            if(ss.isVisible()){
                ss.setVisible(false);
                express.setVisible(false);
            }
        });

    }

    public void send(){//发送按钮点击事件
        chatlist.scrollTo(1000);
        Date date = new Date();
        SimpleDateFormat dateFormat= new SimpleDateFormat("yyyy-MM-dd :hh:mm:ss");
        chat.add(new ChatListData(Local.user.getNickname(),inputbox.getText(),Local.user.getUsername(),"1",dateFormat.format(date)));
        if(Objects.equals(flag, "1")) {
            PrivateChat pc = new PrivateChat();
            pc.privatechattext(Local.user.getUsername(), Local.user.getNickname(), receive, inputbox.getText());//传入发送者id、发送者昵称、接收者id、消息内容
        }//判断是私聊的情况
        else if(Objects.equals(flag, "0")){
            GroupChat gc=new GroupChat();
            gc.GroupChatText(Local.user.getUsername(),Local.user.getNickname(),receive,inputbox.getText());
        }//判断是群聊的情况
        inputbox.setText("");
        chatlist.scrollTo(chatlist.getItems().size());
    }//发送按钮的点击事件

    private void getComboBox(BorderPane borderPane)  {
        VBox vbox = new VBox(); // 创建一个垂直箱子
        // 初始化快餐列表
        List<String> snackList = Arrays.asList("常用语", "你好", "你在干嘛",
                "出来玩嘛", "晚上好！", "早上好！", "中午好！");
        ArrayList<String>a=new ArrayList<String>();
        a.add("在吗");
        a.add("在干嘛");
        ObservableList<String> obList = FXCollections.observableArrayList(Local.commonlist);
        ComboBox<String> comboBox = new ComboBox<String>(obList); // 依据指定数据创建下拉框
        //comboBox.setItems(obList); // 设置下拉框的数据来源
        comboBox.getSelectionModel().select(0); // 设置下拉框默认选中第1项
        Font font = Font.font("NSimSun", 12); // 创建一个字体对象
        comboBox.setStyle(String.format("-fx-font: %f \"%s\";", font.getSize(), font.getFamily())); // 设置下拉框的字体
        comboBox.setEditable(false); // 设置下拉框能否编辑。默认不允许编辑
        vbox.getChildren().addAll(comboBox); // 把水平箱子和标签一起加到垂直箱子上
        // 设置下拉框的选择监听器
        comboBox.getSelectionModel().selectedItemProperty().addListener(new ChangeListener<String>() {
            @Override
            public void changed(ObservableValue<? extends String> arg0, String old_str, String new_str) {
                // getSelectedIndex方法可获得选中项的序号，getSelectedItem方法可获得选中项的对象
               String uti=inputbox.getText();
                inputbox.setText(uti+comboBox.getSelectionModel().getSelectedItem());
            }
        });
        borderPane.setCenter(vbox); // 把垂直箱子放到边界窗格的中央
    }//获取常用语的下拉列表

    public void creatgroup(){//创建群聊的点击事件
        try {
            if(CreatGroupView.loginStage!=null)
                 CreatGroupView.loginStage.close();
            CreatGroupView.start(new Stage());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }//创建群聊的点击事件

    public void onKeyPressed(KeyEvent keyEvent){
        String dd=inputbox.getText();
        if (keyEvent.getCode() == KeyCode.BACK_SPACE&&dd.length()>0) {
            Platform.runLater(()-> {
                int end=dd.length();
                int begin = 0;
                int i=0;
                int flag=1;
                if((dd.charAt(dd.length()-1) + "").equals("]")){
                    for(i=dd.length()-2;i>=0;i--){
                        if((dd.charAt(i) + "").equals("[")) {
                            begin = i;
                            break;
                        }
                        if((dd.charAt(i) + "").equals("]")){
                            flag=0;
                            break;
                        }
                    }
                    if(i>=0&&flag==1)
                        inputbox.deleteText(begin,end-1);
                }
            });

        }//按下回退键的事件
        if(keyEvent.getCode()== KeyCode.ENTER){
            if(Objects.equals(inputbox.getText(), "")){
                 Alert alert = new Alert(Alert.AlertType.INFORMATION);
                 alert.setTitle("提示");
                 alert.setHeaderText("警告");
                 alert.setContentText("发送内容不能为空，请重新输入！");
                 alert.showAndWait();
                Platform.runLater(()-> {
                    ((javafx.scene.control.TextArea) MainWindowView.$("inputbox")).setText("");
                });
            }
            else {
                send();
            }
        }//
    }//将回车键绑定发送按钮

    public void usermessage() {//用户信息的点击事件
        Stage stage=(Stage) nickname.getScene().getWindow();
        stage.close();
        FXMLLoader fxmlLoader = new FXMLLoader();
        fxmlLoader.setLocation(getClass().getResource("usermessage.fxml"));
        Parent root = null;
        try {
            root = fxmlLoader.load();
        } catch (IOException e) {
            e.printStackTrace();
        }
        Stage regitsterstage=new Stage();
        Scene scene = new Scene(root);
        regitsterstage.initStyle(StageStyle.TRANSPARENT);
        MouseFollow in = new MouseFollow(root, regitsterstage);
        regitsterstage.setScene(scene);
        regitsterstage.show();
    }//个人信息的点击事件

    public void xiugaimima(){//修改密码的点击事件
        FXMLLoader fxmlLoader = new FXMLLoader();
        fxmlLoader.setLocation(getClass().getResource("changepwd.fxml"));
        Parent root = null;
        try {
            root = fxmlLoader.load();
        } catch (IOException e) {
            e.printStackTrace();
        }
        Stage regitsterstage=new Stage();
        Scene scene = new Scene(root);
        MouseFollow in = new MouseFollow(root, regitsterstage);
        regitsterstage.setScene(scene);
        regitsterstage.show();
    }//修改密码的点击事件

    public void tianjia(){//打开添加好友界面的点击事件
        try {
            if(AddFriendView.loginStage!=null)
                 AddFriendView.loginStage.close();
            AddFriendView.start(new Stage());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }//搜索好友按钮

    public void tianjiagroup(MouseEvent mouseEvent) {
        try {
            if(AddGroupView.loginStage!=null)
                AddGroupView.loginStage.close();
            AddGroupView.start(new Stage());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }//搜索群聊按钮

    public void tuichu(){
        Message msg=new Message();
        User user=new User();
        user.setUsername(Local.user.getUsername());
        msg.setData(user);
        msg.setMesType(MessageType.MESSAGE_EXIT);
          ClientConnectServerThread clientConnectServerThread=ManageClientConnectServerThread.getClientConnectServerThread(Local.user.getUsername());
        clientConnectServerThread.state=false;
        clientConnectServerThread.send(msg);
        System.exit(0);

    }//无异常退出

    public void smallest(){
        MainWindowView.loginStage.setIconified(true);
    }//最小化按钮的点击事件

    public void sendimage(){
        SelectImage sf=new SelectImage();
        File file=sf.select(createbutton);
        if(file!=null) {
            ChangeImage ci = new ChangeImage();
            byte[] b = ci.get(file);
            SetFile ss = new SetFile();
            ss.set(b, file.getName());
            Date date = new Date();
            SimpleDateFormat dateFormat= new SimpleDateFormat("yyyy-MM-dd :hh:mm:ss");
            chat.add(new ChatListData(Local.user.getNickname(), file.getName(), Local.user.getUsername(), "2",dateFormat.format(date)));
            if (Objects.equals(flag, "1")) {
                PrivateChat pc = new PrivateChat();
                pc.privatechatimage(Local.user.getUsername(), Local.user.getNickname(), receive, file.getName(), b);
            }//判断是私聊的情况
            else if (Objects.equals(flag, "0")) {
                GroupChat gc = new GroupChat();
                gc.groupchatimage(Local.user.getUsername(), Local.user.getNickname(), receive, file.getName(), b);
            }//判断是群聊的情况
        }
    }//发送表情包

    public void sendfile(){
           SelectFile sf=new SelectFile();
           File file=sf.select(createbutton);
           if(file!=null){
               Date date = new Date();
               SimpleDateFormat dateFormat= new SimpleDateFormat("yyyy-MM-dd :hh:mm:ss");
               SendFileThread sendFileThread=new SendFileThread();
               String timestamp= String.valueOf(Calendar.getInstance().getTimeInMillis());
               String time=dateFormat.format(date);
               String address=Local.user.getUsername()+"_"+timestamp+"_";
               sendFileThread.set(file,address);
               sendFileThread.start();
               try {
                   Thread.sleep(500);
               } catch (InterruptedException e) {
                   e.printStackTrace();
               }
               ChatListData cld=new ChatListData(Local.user.getNickname(),address+file.getName(),file.getName(),Local.user.getUsername(),dateFormat.format(date),"3");
                 chat.add(cld);
                if(Objects.equals(flag, "1")){
                     PrivateChat pc=new PrivateChat();
                     pc.privatechatfile(Local.user.getUsername(),Local.user.getNickname(),receive,address,file.getName(),time);
                }
                if(Objects.equals(flag, "0")) {
                      GroupChat gc=new GroupChat();
                      gc.groupchatfile(Local.user.getUsername(),Local.user.getNickname(),receive,address,file.getName(),time);
                }
           }

    }//发送文件的点击事件

    public void expression(MouseEvent mouseEvent) {
        if(ss.isVisible()){
             ss.setVisible(false);
             express.setVisible(false);
        }
        else{
              ss.setVisible(true);
              express.setVisible(true);
        }
        int k=1;
        for(int i=0;i<10;i++) {
            HBox hBox=new HBox();
            for (int j = 0; j < 10; j++) {
                ImageView ee= Expression.getEmojis(k++);
                ee.setFitHeight(30);
                ee.setFitWidth(30);
                hBox.getChildren().add(ee);
            }
            express.getChildren().add(hBox);
        }

    }//表情包选择器的点击事件

    public void commonpharse(){
                Stage stage=(Stage) listview.getScene().getWindow();
                stage.close();
        try {
            CommonPharseView.start(new Stage());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }//常用语的点击事件
}
